package com.pgytesting.secondhandcar.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.pgytesting.secondhandcar.service.RolePowerRelationService;
import com.pgytesting.secondhandcar.vo.ResponseMessage;

import lombok.extern.slf4j.Slf4j;

/**
 * @author : frosty0804@gmail.com
 * @version : v1.0
 * @projectName : SecondHandCar
 * @className : LoginInterceptor
 * @description : TODO(拦截器请求处理类)
 * @date : 2019/6/23 14:46
 */
@Slf4j
public class Interceptor implements HandlerInterceptor {
	
	@Autowired
	private RolePowerRelationService rolePowerRelationService;
    /**
     * Intercept the execution of a handler. Called after HandlerMapping determined an appropriate handler object, but
     * before HandlerAdapter invokes the handler.
     * <p>DispatcherServlet processes a handler in an execution chain, consisting
     * of any number of interceptors, with the handler itself at the end. With this method, each interceptor can decide
     * to abort the execution chain, typically sending a HTTP error or writing a custom response.
     * <p><strong>Note:</strong> special considerations apply for asynchronous
     * request processing. For more details see {@link AsyncHandlerInterceptor}.
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return {@code true} if the execution chain should proceed with the next interceptor or the handler itself. Else,
     * DispatcherServlet assumes that this interceptor has already dealt with the response itself.
     * @throws Exception in case of errors
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	Object userObj = request.getSession().getAttribute("user");
    	
    	request.getRequestURI();
    	if(userObj == null) {
    		log.info("当前处于未登录状态");
    		printJson(response, "未登录，请登录后再试", 600);
    		return false;
    	}
    	
        String userType = String.valueOf(request.getSession().getAttribute("login"));
        String url = request.getRequestURI();
//        switch (userType) {
//            case Parameters.USER_TYPE_USER:
//            	McpUserInfo mu = (McpUserInfo)userObj;
//            	if(!rolePowerRelationService.checkUserPower(mu.getRoleId(), url)) {
//            		log.info("当前用户:"+mu.getUserNumber()+"没有接口:"+url+"的访问权限");
//            		printJson(response, "用户没有接口访问权限", 700);
//            		return false;
//            	}
//            	break;
//            case Parameters.USER_TYPE_CAR:
//            	McpCarDealerInformation mc = (McpCarDealerInformation)userObj;
//            	if(!rolePowerRelationService.checkUserPower(mc.getRoleId(), url)) {
//            		log.info("当前用户:"+mc.getUserNumber()+"没有接口:"+url+"的访问权限");
//            		printJson(response, "用户没有接口访问权限", 700);
//            		return false;
//            	}
//            	break;
//            case Parameters.USER_TYPE_ADMIN:
//            	AdministratorInformation ai = (AdministratorInformation)userObj;
//            	if(!rolePowerRelationService.checkUserPower(ai.getRoleId(), url)) {
//            		log.info("当前用户:"+ai.getUserNumber()+"没有接口:"+url+"的访问权限");
//            		printJson(response, "用户没有接口访问权限", 700);
//            		return false;
//            	}
//            	break;
//        }
//        login = request.getSession().getAttribute("user") == null ? Boolean.FALSE : Boolean.TRUE;
//        System.out.println("登录状态验证状态：" + login);
//        if (login) {
//            response.setStatus(HttpServletResponse.SC_FOUND);
//            response.sendRedirect("/shc/user/isLogin");
//            // 在重定向中增加false，就可以中断请求，如果不中断，则会第一个请求继续请求controller，但是页面会正常重定向
//            return false;
//        }
        return true;
    }

    /**
     * Intercept the execution of a handler. Called after HandlerAdapter actually invoked the handler, but before the
     * DispatcherServlet renders the view. Can expose additional model objects to the view via the given ModelAndView.
     * <p>DispatcherServlet processes a handler in an execution chain, consisting
     * of any number of interceptors, with the handler itself at the end. With this method, each interceptor can
     * post-process an execution, getting applied in inverse order of the execution chain.
     * <p><strong>Note:</strong> special considerations apply for asynchronous
     * request processing. For more details see {@link AsyncHandlerInterceptor}.
     *
     * @param request      current HTTP request
     * @param response     current HTTP response
     * @param handler      handler (or {@link }) that started asynchronous execution, for type and/or instance
     *                     examination
     * @param modelAndView the {@code ModelAndView} that the handler returned (can also be {@code null})
     * @throws Exception in case of errors
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * Callback after completion of request processing, that is, after rendering the view. Will be called on any outcome
     * of handler execution, thus allows for proper resource cleanup.
     * <p>Note: Will only be called if this interceptor's {@code preHandle}
     * method has successfully completed and returned {@code true}!
     * <p>As with the {@code postHandle} method, the method will be invoked on each
     * interceptor in the chain in reverse order, so the first interceptor will be the last to be invoked.
     * <p><strong>Note:</strong> special considerations apply for asynchronous
     * request processing. For more details see {@link AsyncHandlerInterceptor}.
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  handler (or {@link }) that started asynchronous execution, for type and/or instance examination
     * @param ex       exception thrown on handler execution, if any
     * @throws Exception in case of errors
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
    
    private static void printJson(HttpServletResponse response, String str, Integer code) {
    	try {
    		Gson gson =new Gson();
            String content = gson.toJson(ResponseMessage.errorResponse(str, code));
    		
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-store");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(content);
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
